package org.acme.oauth2.resource;

import com.alibaba.fastjson.JSONObject;
import io.quarkus.qute.Template;
import io.quarkus.qute.TemplateInstance;
import org.acme.oauth2.client.TdfOauth2Client;

import org.eclipse.microprofile.config.inject.ConfigProperty;
import org.eclipse.microprofile.rest.client.inject.RestClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.inject.Inject;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import java.io.UnsupportedEncodingException;
import java.util.Base64;

import com.alibaba.fastjson.JSON;

/**
 * @author LiJian
 * @date 2021/7/9 9:24
 */
@Path("/ssologin")
public class TdfOauth2ClientResource {

    private static final Logger LOGGER = LoggerFactory.getLogger(TdfOauth2ClientResource.class);

    @Inject
    @RestClient
    TdfOauth2Client tdfOauth2Client;

    @ConfigProperty(name = "oauth2.server.token.grant_type",defaultValue = "authorization_code")
    String grantType;
    @ConfigProperty(name = "oauth2.server.token.client_id",defaultValue = "tdfuivue")
    String clientId;
    @ConfigProperty(name = "oauth2.server.token.client_secret",defaultValue = "tdfuivue")
    String clientSecret;
    @ConfigProperty(name = "oauth2.server.token.token_url",defaultValue = "")
    String tokenUrl;
    @ConfigProperty(name = "oauth2.server.token.userInfoUrl",defaultValue = "")
    String userInfoUrl;
    @ConfigProperty(name = "oauth2.server.token.redirect_url",defaultValue = "")
    String redirectUrl;
    @Inject
    Template login;

    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public TemplateInstance getCode(@QueryParam("code") String code,
                                    @QueryParam("state") String state) throws UnsupportedEncodingException {
        System.out.println(code);
        LOGGER.info("授权码获取成功："+code);
        if(code!=null) {
            String codeAuthorization= clientId+":"+clientSecret;
            final byte[] textByte = codeAuthorization.getBytes("UTF-8");
            final Base64.Encoder encoder = Base64.getEncoder();
            //编码
            final String encodedText = encoder.encodeToString(textByte);
            //携带code获取access_token
            String tokenBody=tdfOauth2Client.getAccessToken(code,grantType,redirectUrl,"Basic "+encodedText);
            JSONObject jo = JSON.parseObject(tokenBody);
            if(jo.containsKey("access_token")){
                //获取access_token
                String token = jo.getString("access_token");
                LOGGER.info("token获取成功"+token);
                //携带access_token获取用户信息
                String getUser=tdfOauth2Client.getUserMessage("Bearer "+token);
                LOGGER.info("用户信息获取成功："+getUser);
                return login.data("clientId",getUser);
            }
            else{
                return login.data("clientId","获取token失败！");
            }
        }else{
            return login.data("clientId","授权码获取失败！");
        }
    }
}
